package net.wanho.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import net.wanho.properties.JwtProperties;

import java.util.Calendar;
import java.util.Map;

/**
 * JWT工具类
 */
public class JwtUtil {

    private static final String SECRET; // 密钥
    private static final int EXPIRE; // 过期时间(分钟)

    static {
        try {
            JwtProperties jwtProperties = ApplicationContextHolder.getBean(JwtProperties.class);
            SECRET = jwtProperties.getSecret();
            EXPIRE = jwtProperties.getExpire();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    /**
     * 生成令牌
     * @param payload 载荷
     * @return
     */
    public static String generate(Map<String, Object> payload) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, EXPIRE);

        String token = JWT.create()
                .withPayload(payload)
                .withExpiresAt(calendar.getTime())
                .sign(Algorithm.HMAC256(SECRET));
        return token;
    }

    /**
     * 校验令牌
     * @param token 令牌串
     * @return 校验成功返回true，校验失败抛出异常
     */
    public static boolean valid(String token) {
        try {
            JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
            return true;
        } catch (RuntimeException e) {
            throw e;
        }
    }

    /**
     * 解析令牌
     * @param token 令牌串
     * @param key 令牌键
     * @return
     */
    public static Integer parseInteger(String token, String key) {
        DecodedJWT decodedJWT = JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
        return decodedJWT.getClaim(key).asInt();
    }

    public static Long parseLong(String token, String key) {
        DecodedJWT decodedJWT = JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
        return decodedJWT.getClaim(key).asLong();
    }

    public static String parseString(String token, String key) {
        DecodedJWT decodedJWT = JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
        return decodedJWT.getClaim(key).asString();
    }

    /**
     * 反码令牌
     * @param token 令牌串
     * @param key 令牌键
     * @return
     */
    public static Integer decodeInteger(String token, String key) {
        DecodedJWT decodedJWT = JWT.decode(token);
        return decodedJWT.getClaim(key).asInt();
    }

    public static Long decodeLong(String token, String key) {
        DecodedJWT decodedJWT = JWT.decode(token);
        return decodedJWT.getClaim(key).asLong();
    }

    public static String decodeString(String token, String key) {
        DecodedJWT decodedJWT = JWT.decode(token);
        return decodedJWT.getClaim(key).asString();
    }

}
